<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Form Submission</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 20px;
        }
        .container {
            background-color: #fff;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            width: 80%;
            max-width: 800px;
            margin: 20px auto;
        }
        form {
            display: flex;
            flex-direction: column;
            gap: 15px;
            margin-bottom: 20px;
        }
        label {
            font-weight: bold;
        }
        input[type="text"],
        input[type="email"] {
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 3px;
            width: 100%;
            box-sizing: border-box;
        }
        .button-container {
            display: flex;
            gap: 10px;
            margin: 20px 0;
        }
        button, input[type="submit"] {
            padding: 10px;
            background-color: #5cb85c;
            color: white;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            flex: 1;
        }
        button:hover, input[type="submit"]:hover {
            background-color: #4cae4c;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 12px;
            text-align: left;
        }
        th {
            background-color: #f8f8f8;
        }
        tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        tr:hover {
            background-color: #f5f5f5;
        }
        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            margin-top: 20px;
            gap: 5px;
        }
        .pagination button {
            padding: 8px 12px;
            border: 1px solid #ddd;
            background-color: white;
            color: #333;
            cursor: pointer;
            border-radius: 4px;
            transition: all 0.3s ease;
            font-size: 14px;
        }
        /* 上一页和下一页按钮的样式 */
        .pagination button:first-child,
        .pagination button:last-child {
            min-width: 75px;
            font-weight: normal;
        }
        /* 数字按钮的样式 */
        .pagination button:not(:first-child):not(:last-child) {
            min-width: 32px;
            padding: 6px 8px;
            font-size: 12px;
        }
        .pagination button:hover:not(:disabled) {
            background-color: #f8f9fa;
            border-color: #ddd;
            color: #0d6efd;
        }
        .pagination button.active {
            background-color: #1890ff;
            color: white;
            border-color: #1890ff;
        }
        .pagination button:disabled {
            background-color: #f4f4f4;
            color: #999;
            cursor: not-allowed;
        }
        .pagination-info {
            margin: 10px 0;
            text-align: center;
            color: #666;
            font-size: 14px;
        }
        .error-details {
            margin-top: 10px;
            font-size: 0.9em;
            color: #666;
        }
        .error-field {
            color: #a94442;
            font-weight: bold;
        }
        .error-message {
            margin-top: 5px;
            padding: 5px;
            background-color: #f8f8f8;
            border-left: 3px solid #a94442;
        }
        .custom-alert {
            display: none;
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            padding: 15px 25px;
            border-radius: 4px;
            font-size: 16px;
            z-index: 1000;
            min-width: 300px;
            max-width: 80%;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            text-align: center;
        }
        
        .custom-alert.success {
            background-color: #5cb85c;
            color: white;
            border: none;
        }
        
        .custom-alert.error {
            background-color: #d9534f;
            color: white;
            border: none;
        }
        
        .error-details {
            margin-top: 10px;
            font-size: 0.9em;
            text-align: left;
            padding: 10px;
            background-color: rgba(255, 255, 255, 0.9);
            border-radius: 3px;
            color: #333;
        }

        @keyframes slideInDown {
            from {
                transform: translate(-50%, -100%);
                opacity: 0;
            }
            to {
                transform: translate(-50%, 0);
                opacity: 1;
            }
        }

        @keyframes slideOutUp {
            from {
                transform: translate(-50%, 0);
                opacity: 1;
            }
            to {
                transform: translate(-50%, -100%);
                opacity: 0;
            }
        }

        .slide-in {
            animation: slideInDown 0.3s ease-out forwards;
        }

        .slide-out {
            animation: slideOutUp 0.3s ease-out forwards;
        }

        /* 修改遮罩层样式 */
        .modal-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.1);
            z-index: 999;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .modal-overlay.show {
            opacity: 1;
        }
    </style>
    <script>
        // 创建遮罩层
        function createOverlay() {
            if (!document.getElementById('modalOverlay')) {
                const overlay = document.createElement('div');
                overlay.id = 'modalOverlay';
                overlay.className = 'modal-overlay';
                document.body.appendChild(overlay);
            }
            return document.getElementById('modalOverlay');
        }

        // 创建自定义提示框
        function createAlertElement() {
            if (!document.getElementById('customAlert')) {
                const alertDiv = document.createElement('div');
                alertDiv.id = 'customAlert';
                alertDiv.className = 'custom-alert';
                document.body.appendChild(alertDiv);
            }
            return document.getElementById('customAlert');
        }

        // 显示自定义提示框
        function showAlert(message, isSuccess, errorDetails = null) {
            const alertElement = createAlertElement();
            const overlay = createOverlay();
            
            alertElement.className = 'custom-alert ' + (isSuccess ? 'success' : 'error');
            
            let content = message;
            
            if (!isSuccess && errorDetails) {
                content += '<div class="error-details">';
                if (errorDetails.error) {
                    content += `<div>错误类型: ${errorDetails.error}</div>`;
                }
                if (errorDetails.message) {
                    content += `<div>错误信息: ${errorDetails.message}</div>`;
                }
                if (errorDetails.path) {
                    content += `<div>请求路径: ${errorDetails.path}</div>`;
                }
                content += '</div>';
            }
            
            alertElement.innerHTML = content;
            alertElement.style.display = 'block';
            overlay.style.display = 'block';
            
            // 使用 requestAnimationFrame 确保过渡效果正常工作
            requestAnimationFrame(() => {
                alertElement.classList.add('slide-in');
                overlay.classList.add('show');
            });
            
            // 2秒后自动消失
            setTimeout(() => {
                alertElement.classList.remove('slide-in');
                alertElement.classList.add('slide-out');
                overlay.classList.remove('show');
                
                setTimeout(() => {
                    alertElement.style.display = 'none';
                    overlay.style.display = 'none';
                    alertElement.classList.remove('slide-out');
                }, 300);
            }, 2000);
        }

        function handleErrorResponse(xhr) {
            try {
                const errorResponse = JSON.parse(xhr.responseText);
                showAlert('操作失败', false, errorResponse);
            } catch (e) {
                showAlert('操作失败: ' + xhr.statusText, false);
            }
        }

        function validateForm() {
            const name = document.getElementById('name').value;
            const email = document.getElementById('email').value;
            const salary = document.getElementById('salary').value;

            if (!name || name.trim() === '') {
                showAlert('员工姓名不能为空！', false);
                return false;
            }

            if (!email || email.trim() === '') {
                showAlert('员工邮箱不能为空！', false);
                return false;
            }

            if (!salary || isNaN(salary) || parseFloat(salary) < 0) {
                showAlert('薪资必须是大于等于0的数字！', false);
                return false;
            }

            return true;
        }

        let currentPage = 1;  // 当前页码
        const pageSize = 5;   // 每页显示5条数据
        let totalItems = 0;   // 总数据条数

        // 获取指定页的员工数据
        function refreshEmployeeList(page) {
            //XMLHttpRequest是浏览器提供的一个js对象，用于网页中和服务器进行数据交互，无需刷新整个页面，是实现AJAX的核心
            var xhr = new XMLHttpRequest();
            xhr.open('GET', `/employees/page?pageNumber=${page}&pageSize=${pageSize}`, true);
            //设置回调函数，处理响应
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    //处理响应数据
                    //把返回的数据转换为json格式
                    const response = JSON.parse(xhr.responseText);
                    console.log(response);
                    // 从后端返回的PageInfo对象中获取数据
                    const employees = response.list;
                    console.log(employees);
                    totalItems = response.total;
                    
                    // 显示当前页的数据
                    displayEmployees(employees);
                    
                    // 更新分页按钮
                    updatePaginationButtons();
                }
            };
            //发送请求
            xhr.send();
            console.log('请求已发送，但回调可能还未执行');
        }

        // 显示指定页的数据
        function showPage(page) {
            currentPage = page;
            refreshEmployeeList(page);
        }

        // 更新分页按钮
        function updatePaginationButtons() {
            const totalPages = Math.ceil(totalItems / pageSize);
            //分页按钮的容器
            const pagination = document.getElementById('pagination');
            //显示分页信息
            const paginationInfo = document.getElementById('paginationInfo');
            
            // 清空现有按钮
            pagination.innerHTML = '';
            
            // 创建上一页按钮
            const prevButton = document.createElement('button');    //动态创建一个新的按钮
            prevButton.textContent = '上一页';
            prevButton.disabled = currentPage === 1;     //当显示的是第一页的时候禁用，即没有上一页
            prevButton.onclick = () => showPage(currentPage - 1);  //点击时跳转到上一页
            pagination.appendChild(prevButton);    //将“上一页”的按钮添加到分页控件的容器中
            
            // 计算要显示的三个页码
            let startPage = currentPage - 1;
            if (startPage < 1) {
                startPage = 1;
            } else if (startPage > totalPages - 2) {
                startPage = Math.max(1, totalPages - 2);
            }
            
            // 创建三个页码按钮
            for (let i = 0; i < 3 && (startPage + i) <= totalPages; i++) {
                const pageNum = startPage + i;
                const pageButton = document.createElement('button');   //创建页码按钮
                pageButton.textContent = pageNum;
                if (pageNum === currentPage) {
                    pageButton.classList.add('active');    //为页码添加一个名为active的css类，高亮显示当前页码
                }
                pageButton.onclick = () => showPage(pageNum);
                pagination.appendChild(pageButton);   //将页码按钮添加到分页控件的容器中
            }
            
            // 创建下一页按钮
            const nextButton = document.createElement('button');   //动态创建一个新的按钮
            nextButton.textContent = '下一页';
            nextButton.disabled = currentPage === totalPages;     //如果当前页是最后一页，则禁用下一页按钮
            nextButton.onclick = () => showPage(currentPage + 1);     //点击下一页之后会显示下一页的数据
            pagination.appendChild(nextButton);         //将“下一页”按钮添加到分页控件的容器中
            
            // 更新分页信息
            paginationInfo.textContent = `第 ${currentPage} 页 / 共 ${totalPages} 页，总计 ${totalItems} 条记录`;
        }

        // 显示员工数据
        function displayEmployees(employees) {
            //找到表格和表格的内容区域
            var tbody = document.getElementById('employeesTable').getElementsByTagName('tbody')[0];
            tbody.innerHTML = ''; // 清空表格内容

            //当没有数据时，显示一个友好的提示
            if (employees.length === 0) {
                var row = tbody.insertRow();
                var cell = row.insertCell();
                cell.colSpan = 4;
                cell.style.textAlign = 'center';
                cell.textContent = '暂无数据';
                return;
            }

            //遍历员工数据
            employees.forEach(function(employee) {
                //为每一个员工创建一个表格行
                var row = tbody.insertRow();
                //对数组中的每一个元素执行一次操作，field是数组名
                ['id', 'name', 'email', 'salary'].forEach(function(field) {
                    //创建单元格
                    var cell = row.insertCell();
                    //为单元格设置内容
                    cell.textContent = employee[field];
                });
            });
            //找到id为employeesTable的表格，设置样式为表格
            
            document.getElementById('employeesTable').style.display = 'table';
        }

        // 页面加载完成后自动加载第一页数据
        // window.onload = function() {
        //     showPage(1);
        // };

        function submitFormAsGet() {
            showPage(1);
            showAlert('数据获取成功！', true);
        }

        function submitFormAsPost() {
            if (!validateForm()) {
                return;
            }

            var form = document.getElementById('myForm');
            var formData = new FormData(form);
            var data = {};
            formData.forEach((value, key) => data[key] = value);

            var xhr = new XMLHttpRequest();
            xhr.open('POST', '/employees', true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        showAlert('添加成功！', true);
                        form.reset(); // 清空表单
                        showPage(1); // 刷新到第一页
                    } else {
                        handleErrorResponse(xhr);
                    }
                }
            };
            xhr.send(JSON.stringify(data));
        }

        function submitFormAsPut() {
            if (!validateForm()) {
                return;
            }

            var form = document.getElementById('myForm');
            var formData = new FormData(form);
            var data = {};
            formData.forEach((value, key) => data[key] = value);

            var xhr = new XMLHttpRequest();
            xhr.open('PUT', '/employees', true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        showAlert('更新成功！', true);
                        form.reset(); // 清空表单
                        showPage(currentPage); // 刷新当前页
                    } else {
                        handleErrorResponse(xhr);
                    }
                }
            };
            xhr.send(JSON.stringify(data));
        }

        function submitFormAsDelete() {
            var id = document.getElementById('id').value;
            if (!id) {
                showAlert('请输入要删除的员工ID', false);
                return;
            }

            var xhr = new XMLHttpRequest();
            xhr.open('DELETE', '/employees/' + id, true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        showAlert('删除成功！', true);
                        document.getElementById('myForm').reset(); // 清空表单
                        showPage(currentPage); // 刷新当前页
                    } else {
                        handleErrorResponse(xhr);
                    }
                }
            };
            xhr.send();
        }
    </script>
</head>
<body>
    <div class="container">
        <form id="myForm" action="/employees" method="post">
            <div>
                <label for="id">Id:</label>
                <input type="text" id="id" name="id" required>
            </div>
            <div>
                <label for="name">Name:</label>
                <input type="text" id="name" name="name" required>
            </div>
            <div>
                <label for="email">Email:</label>
                <input type="email" id="email" name="email" required>
            </div>
            <div>
                <label for="salary">Salary:</label>
                <input type="text" id="salary" name="salary" required>
            </div>
            <input type="submit" value="PUT 提交" onclick="submitFormAsPut(); return false;">
        </form>
        <div class="button-container">
            <button onclick="submitFormAsGet();">GET 请求</button>
            <button onclick="submitFormAsPost();">POST 请求</button>
            <button onclick="submitFormAsDelete();">DELETE 请求</button>
        </div>
        <table id="employeesTable">
            <thead>
                <tr>
                    <th>Id</th>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Salary</th>
                </tr>
            </thead>
            <tbody>
                <!-- 员工数据将在这里显示 -->
            </tbody>
        </table>
        
        <!-- 添加分页信息显示 -->
        <div id="paginationInfo" class="pagination-info"></div>
        
        <!-- 分页控件容器 -->
        <div id="pagination" class="pagination">
            <!-- 分页按钮将在这里显示 -->
        </div>
    </div>
</body>
</html>
